<template>
  <div>
    <el-tree
      ref="tree"
      :data="list"
      :props="{children: 'children',
               label: 'name'}"
      show-checkbox
      node-key="id"
      default-expand-all
    />
    <template>
      <div style="text-align: right;">
        <el-button @click="$emit('close')">取消</el-button>
        <el-button type="primary" @click="hSubmit">确定</el-button>
      </div>
    </template>
  </div>
</template>

<script>
import { getPermissionList } from '@/api/permisson'
import { transDataToTreeData } from '@/utils/index'
import { getRoleDetail, assignPerm } from '@/api/settings'

export default {
  props: {
    roleId: {
      type: String,
      required: true
    }
  },
  data() {
    return {
      list: [] // 存储权限数据
    }
  },
  created() {
    this.loadPermissionList()
    this.getRoleDetail()
  },
  methods: {
    async hSubmit() {
      const permIds = this.$refs.tree.getCheckedKeys()
      try {
        const res = await assignPerm({ id: this.roleId, permIds: permIds })
        console.log('assignPerm', res)
        this.$emit('close')
        // 保存数据
      } catch (err) {
        console.log('assignPerm', err)
      }
    },
    // 获取角色详情
    async getRoleDetail() {
      try {
        const res = await getRoleDetail(this.roleId)
        console.log('getRoleDetail', res)
        this.$refs.tree.setCheckedKeys(res.data.permIds)
        // 保存数据
      } catch (err) {
        console.log('getRoleDetail', err)
      }
    },
    // 获取所有的数据
    async loadPermissionList() {
    // 发送请求, 获取权限列表
      const res = await getPermissionList()
      console.log('权限列表的数据是', res)
      this.list = transDataToTreeData(res.data)
    }
  }
}
</script>

<style>

</style>
